#pragma once;
#include "data.hpp"
#include "httplib.h"
#include <windows.h>


namespace cloud
{
#define SERVER_ADDR "43.143.132.22"
#define SERVER_PORT 8081
	class Backup
	{
	private:
		std::string _back_dir;
		DataManager* _data;
	public:
		Backup(const std::string& backup_dir, const std::string& back_file)
		{
			_back_dir = backup_dir;
			_data = new DataManager(back_file);
		}

		std::string GetFileIdentifier(std::string filename)
		{
			// a.txt-fsize-mtime;
			FileUtil fu(filename);
			std::stringstream ss;
			ss << fu.FileName() << "-" << fu.FileSize() << "-" << fu.LastModifyTime();
			return ss.str();
		}

		bool Upload(const std::string& filename)
		{
			// 1. get all data
			FileUtil fu(filename);
			std::string body;
			fu.GetContent(body);

			// 2. send data to client
			httplib::Client client(SERVER_ADDR, 8081); 
			httplib::MultipartFormData item;
			item.content = body;
			item.filename = fu.FileName();
			item.name = "file"; // mark
			item.content_type = "application/octet-stream";

			httplib::MultipartFormDataItems items;
			items.push_back(item);
			auto res = client.Post("/upload", items);
			if (!res || res->status != 200)
			{
				return false;
			}
			return true;
		}

		bool IsNeedUpload(const std::string& filename)
		{
			// we have two condition to judge if the file is new
			// 1. we don have the info in the table
			// 2. the unicode change
			std::string id;
			if (_data->GetOneByKey(filename, id) == false)
			{
				return true;
			}

			std::string new_id = GetFileIdentifier(filename);
			if (new_id == id)
			{
				return false;
			}
			// copy need time 
			// so if the file has big content we will continue upload it 
			FileUtil fu(filename);
			if (time(NULL) - fu.LastModifyTime() < 3)
			{
				return false;
			}
			return true;
		}

		bool Runmodule()
		{
			while (1)
			{
				FileUtil fu(_back_dir);
				std::vector<std::string> arry;
				fu.ScanDirectory(arry);


				for (auto a : arry)
				{
					if (IsNeedUpload(a) == false)
					{
						continue;
					}
					
					if (Upload(a) == true)
					{
						_data->Insert(a, GetFileIdentifier(a));
					}
				}
				// judge if the file need upload

				Sleep(100);
			}
		}
	};
}
